// 记录消息
function addMessageRecord(message) {
    chatHistory.push(message);
    if (chatHistory.length > 6) {
        chatHistory.shift();
    }
}

addMessageRecord({
    "role": "ai",
    "text": $("#chat-box .content .chat-item:first .text").text()
})

// 插入消息
function newMessage(role, think=null, text=null) {
    let message = $("<div></div>");
    message.addClass("chat-item");
    message.addClass(role);
    if (role == "ai") {
        let avatar = $("<span></span>")
        avatar.addClass("avatar");
        let avatarImg = $("<img>");
        avatarImg.attr("src", "../static/images/avatar.svg");
        avatar.append(avatarImg);
        message.append(avatar);
    }
    let messageDiv = $("<div></div>");
    messageDiv.addClass("message");

    thinkSpan = $("<span></span>").css("display", "none");
    thinkSpan.addClass("think");
    if (think !== null) {
        thinkSpan.text(think);
        thinkSpan.css("display", "inline-block");
    }
    messageDiv.append(thinkSpan);

    textSpan = $("<span></span>");
    textSpan.addClass("text");
    if (text === null) {
        text = "正在思考中..."
    }
    textSpan.text(text);
    messageDiv.append(textSpan);

    message.append(messageDiv);

    $("#chat-box .content").append(message);

    // 自动滚动到底部
    $("#chat-box .content").scrollTop($("#chat-box .content")[0].scrollHeight);

    return messageDiv;
}

// 发送消息
async function requestAI (e=null) {
    if (e === null) {
        e = newMessage('ai');
    }
    const url = '/api/ai_move';
    const data = {historyMessage: chatHistory};
    const response = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    });
    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';
    let isMove = false
    let isError = false
    let errorMsg = ''
    while (true) {
        const { done, value } = await reader.read();
        if (done) {
            break;
        }
        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop();

        let isShowThink = false;
        for (const line of lines) {
            if (!line.startsWith('data: ')) {
                continue;
            }
            let message = line.slice(5).trim();
            if (!message) {
                continue;
            }
            message = JSON.parse(message);
            if (message.type === 'think') {
                if (!isShowThink) {
                    e.children('.think').show();
                    isShowThink = true;
                }
                e.children('.think').append(message.data);
            } else if (message.type === 'message') {
                e.children('.text').text(JSON.stringify(message.data))

                isMove = true
                console.log(message.data);
                const data = message.data;
                const pieceID = data.id
                const pieceColor = pieceID[0] == 'r' ? 'red' : 'black'
                const pieceColorCN = pieceColor === 'r' ? '红' : '黑'

                // 使用ID获取棋子
                const pieceByID = $('#' + data.id)

                // 使用位置获取棋子
                const pieceByPos = getPiece(data.from.x, data.from.y)

                // 棋子不存在
                if (pieceByID.length === 0) {
                    isError = true
                    errorMsg = '`' + pieceID + '`不存在，请重新思考。'
                }
                if (pieceByPos === null) {
                    isError = true
                    errorMsg = '`' + data.from.string + '`没有棋子，请重新思考。'
                }

                // 棋子位置不对
                if (pieceByID.data('x') !== data.from.x || pieceByID.data('y') !== data.from.y) {
                    isError = true
                    errorMsg = '`' + data.from.string + '`上的棋子并不是`' + pieceID +'`，请重新思考。'
                }

                // 棋子颜色不对
                if (pieceColor === userHolderColor) {
                    const aiColor = userHolderColor === 'red' ? '黑' : '红'
                    isError = true
                    errorMsg = "你拿错颜色的棋子了，你应该拿" + aiColor + "棋，请重新思考。"
                }

                // 拿棋
                pieceByID.click()

                // 落子位置错误
                let allowPosString = []
                let isAllow = false
                let allowPiece = null
                $('.allowed-move').each(function() {
                    const x = $(this).data('x')
                    const y = $(this).data('y')
                    const xString = getXString(x)
                    const yString = getYString(y)
                    allowPosString.push(yString + xString)
                    if (x === data.to.x && y === data.to.y) {
                        isAllow = true
                        allowPiece = $(this)
                    }
                })
                if (!isAllow) {
                    pieceByID.click()
                    isError = true
                    errorMsg = '`' + pieceID + '`不允许落在`' + data.to.string + '`，请重新思考。'
                } else {
                    allowPiece.click()
                    return;
                }
            }
        }
    }
    if (!isMove) {
        isError = true
        errorMsg = '你没有给出落子的JSON数据，请重新思考。'
        e.children('.text').text('无')
    }
    if (isError) {
        console.log(errorMsg)
        newMessage('user', think=null, text=errorMsg);
        addMessageRecord({
            'role': 'ai',
            'text': e.children('.text').text()
        })
        addMessageRecord({
            'role': 'user',
            'text': errorMsg,
            'board': boardToArray()
        })
        requestAI();
        return;
    }
}